package nl.xvr.server.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.Semaphore;

import nl.xvr.server.control.ControlServer;
import nl.xvr.server.web.WebServer;

public class Main {
    public static final String CONFIGPATH = "D:/EclipseWorkspace/os_server/resources/server.properties";

    /**
     * @param args
     */
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(0);
        
        try {
            Properties properties = loadProperties();

            WebServer ws = new WebServer(properties);
            ControlServer cs = new ControlServer(properties, semaphore);

            ws.start();
            cs.start();

            while(true) {
                semaphore.acquire();
                System.out.println("Stop waiting...");
                Properties temp = loadProperties();
                if(temp.size() == properties.size() && !properties.equals(temp)) {
                    System.out.println("Properties have been changed!");
                    ws.closeServer();
                    cs.closeServer();
                    //Starting new servers
                    ws = new WebServer(temp);
                    cs = new ControlServer(temp, semaphore);
                    cs.start();    
                    ws.start();
                    
                    properties = temp;                    
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            System.exit(-1);
        }
    }

    private static Properties loadProperties() {
        Properties properties = new Properties();
        InputStream is = null;
        try {
            is = new FileInputStream(new File(CONFIGPATH));
            properties.load(is);
        } catch(IOException e) {
            System.out.println(e);
        }
        return properties;
    }
}
